package com.leyou.auth.config;

import com.leyou.common.auth.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/14 0014
 * Time: 21:14
 */
@Data
@Slf4j
@ConfigurationProperties(prefix = "ly.jwt")
public class JwtProperties implements InitializingBean {
    /**
     * 公钥地址
     */
    private String pubKeyPath;
    /**
     * 私钥地址
     */
    private String privateKeyPath;
    /**
     * 用于初始化后就赋值
     */
    private PublicKey publicKey;
    private PrivateKey privateKey;

    /**
     * 微服务认证token
     */
    private PrivilegeTokenProperties privilege = new PrivilegeTokenProperties();

    @Data
    public class PrivilegeTokenProperties {
        /**
         * 服务ID
         */
        private Long id;
        /**
         * 存放服务认证token的请求头
         */
        private String headerName;
        /**
         * 服务秘钥
         */
        private String secret;
        /**
         * 微服务认证token的过期时长
         */
        private int expire;

    }

    /**
     * 用户token相关属性
     */
    private UserTokenProperties user = new UserTokenProperties();

    @Data
    public class UserTokenProperties {
        /**
         * token过期时长
         */
        private int expire;
        /**
         * 存放token的cookie名称
         */
        private String cookieName;
        /**
         * 存放token的cookie的domain
         */
        private String cookieDomain;
        /**
         * 最小刷新时间 间隔
         */
        private int minRefreshInterval;
    }

    /**
     * 初始化公钥和私钥进行赋值
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(privateKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥和私钥失败！", e);
            throw new RuntimeException(e);
        }
    }
}
